package org.lzy.shop.order

import android.content.Intent
import android.net.Uri
import android.text.TextUtils
import android.util.Log
import android.view.ViewGroup
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.XXPermissions
import com.hjq.permissions.permission.PermissionLists
import com.hjq.permissions.permission.base.IPermission
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.lzy.shop.Constant
import org.lzy.shop.R
import org.lzy.shop.adapter.ChoosePicAdapter
import org.lzy.shop.base.BaseMvvmActivity
import org.lzy.shop.databinding.ActivityCommentGoodBinding
import org.lzy.shop.datas.Data
import org.lzy.shop.datas.OrderCommentRequest
import org.lzy.shop.util.FileManager
import org.lzy.shop.view.TakePhoto
import org.lzy.shop.viewmodel.OrderModel
import top.zibin.luban.OnCompressListener
import java.io.File
import java.lang.ref.WeakReference

/**
 * 评论订单
 */
class OrderCommentActivity : BaseMvvmActivity<ActivityCommentGoodBinding, OrderModel>({ ActivityCommentGoodBinding.inflate(it) }) {
    var orderID = 0
    var goodsID = 0
    private var mChoosePicAdapter: ChoosePicAdapter? = null
    private var takePhoto: TakePhoto? = null

    //相册回调
    private var mActivityResultLauncherAlbum: ActivityResultLauncher<Intent>? = null

    //选择的相册图片以Uri格式存储
    private val selectedFilesAll = ArrayList<Uri>()
    //压缩后的图片路径
    private val compressedImagePaths = mutableListOf<String>()

    override fun initView() {
        setTitleText(getResString(R.string.order_comment))

        //获取订单ID和商品ID
        if (intent.extras != null) {
            val bundle = intent.extras
            orderID = bundle!!.getInt(Constant.ORDERID)
            goodsID = bundle.getInt(Constant.GOODID)
        }

        takePhoto = TakePhoto(WeakReference(this))
        registerActivityResult()

        //初始化图片适配器，设置最大选择数量为9
        mChoosePicAdapter = ChoosePicAdapter(this, 9)
        binding.choosepicRv.apply {
            layoutManager = GridLayoutManager(this@OrderCommentActivity, 3)
            adapter = mChoosePicAdapter
            layoutParams.height = ViewGroup.LayoutParams.WRAP_CONTENT
            setHasFixedSize(false)
        }

        //设置图片选择监听器
        mChoosePicAdapter?.setOnAddPicturesListener(object : ChoosePicAdapter.OnAddPicturesListener {
            override fun onAdd() {
                //检查是否已达到最大选择数量
                if (selectedFilesAll.size >= 9) {
                    showToast("最多只能选择9张图片")
                    return
                }
                openAlbum()
            }

            override fun delete(position: Int) {
                //移除图片
                if (position < selectedFilesAll.size) {
                    selectedFilesAll.removeAt(position)
                }
                if (position < compressedImagePaths.size) {
                    compressedImagePaths.removeAt(position)
                }
                mChoosePicAdapter?.removeImage(position)
            }
        })
    }

    //打开相册，支持多选
    private fun openAlbum() {
        XXPermissions.with(this)
            //申请存储权限
            .permission(PermissionLists.getManageExternalStoragePermission())
            .request(object : OnPermissionCallback {
                override fun onGranted(permissions: MutableList<IPermission>, allGranted: Boolean) {
                    if (!allGranted) {
                        showToast("需要存储权限才能选择图片")
                        return
                    }

                    //使用Intent.ACTION_GET_CONTENT支持多选
                    val intentAlbum = Intent(Intent.ACTION_GET_CONTENT)
                    intentAlbum.type = "image/*"
                    intentAlbum.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)
                    intentAlbum.addCategory(Intent.CATEGORY_OPENABLE)
                    mActivityResultLauncherAlbum?.launch(intentAlbum)
                }

                override fun onDenied(permissions: MutableList<IPermission>, doNotAskAgain: Boolean) {
                    if (doNotAskAgain) {
                        //如果是被永久拒绝就跳转到应用权限系统设置页面
                        XXPermissions.startPermissionActivity(this@OrderCommentActivity, permissions)
                    } else {
                        showToast("需要存储权限才能选择图片")
                    }
                }
            })
    }

    private fun registerActivityResult() {
        mActivityResultLauncherAlbum = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {result ->
            if (result.resultCode == RESULT_OK) {
                // 使用协程处理图片，避免UI线程阻塞
                lifecycleScope.launch(Dispatchers.IO) {
                    val clipData = result.data?.clipData
                    if (clipData != null) {
                        //处理多选情况
                        val count = clipData.itemCount
                        val remainingSlots = 9 - selectedFilesAll.size
                        val actualCount = count.coerceAtMost(remainingSlots)

                        if (actualCount <= 0) {
                            showToast("最多只能选择9张图片")
                            return@launch
                        }

                        for (i in 0 until actualCount) {
                            val uri = clipData.getItemAt(i).uri
                            if (uri != null) {
                                selectedFilesAll.add(uri)
                                handleSelectedImage(uri)
                            }
                        }
                    } else if (result.data?.data != null) {
                        //处理单选情况
                        val uri = result.data?.data
                        if (uri != null && selectedFilesAll.size < 9) {
                            selectedFilesAll.add(uri)
                            handleSelectedImage(uri)
                        } else if (selectedFilesAll.size >= 9) {
                            showToast("最多只能选择9张图片")
                        }
                    }

                }
            }
        }
    }

    //处理选择的图片，进行压缩并显示
    private fun handleSelectedImage(uri: Uri) {
        lifecycleScope.launch {
            try {
                val file: File? = FileManager.getMediaUri2File(this@OrderCommentActivity,uri)
                val filePath = file?.absolutePath

                if (!TextUtils.isEmpty(filePath)) {
                    // 创建一个CompletableDeferred来等待图片压缩完成
                    val compressedFileDeferred = CompletableDeferred<File?>()
                    withContext(Dispatchers.Main) {
                        takePhoto?.compressPicture(filePath, object : OnCompressListener {
                            override fun onStart() {
                                showLoading()
                            }

                            override fun onSuccess(compressedFile: File?) {
                                dismissLoading()
                                compressedFileDeferred.complete(compressedFile)
                            }

                            override fun onError(e: Throwable?) {
                                dismissLoading()
                                compressedFileDeferred.completeExceptionally(e ?: Exception("图片压缩失败"))
                            }

                        })

                    }
                }
            } catch (e: Exception) {
                withContext(Dispatchers.Main) {
                    // 检查Activity状态，避免内存泄漏
                    if (!isFinishing && !isDestroyed) {
                        showToast("处理图片失败，请重试")
                    }
                }
            }

        }
    }

    override fun requestData() {
        //无需初始化请求数据
    }

    override fun initData() {
        //评论提交相关的数据监听
        mViewModel.ossUploadLiveData.observeWithLifecycle(this) {
            it?.let {ossUpload ->
                //获取腾讯OSS凭证后上传图片
                mViewModel.uploadImages(
                    this,
                    selectedFilesAll,
                    ossUpload.url,
                    ossUpload.credentials.tmpSecretId,
                    ossUpload.credentials.tmpSecretKey,
                    ossUpload.credentials.sessionToken
                )
            }
        }

        mViewModel.uploadImgLiveData.observeWithLifecycle(this) {
            it?.let {localPath ->
                //创建评论数据
                val comment = Data(
                    binding.input.text.toString(),
                    goodsID,
                    orderID,
                    mutableListOf(localPath), //简化处理，实际可能需要调整
                    binding.commentBar.numStars
                )
                val request = OrderCommentRequest(comment, orderID.toString())
                mViewModel.orderComment(request)
            }
        }

        mViewModel.orderCommentData.observeWithLifecycle(this) {
            showSuccessToast("评论成功")
            //评论成功后可以返回上一页
            finish()
        }
    }

    override fun allClick() {
        binding.orderCommentBtn.setOnClickListener {
            if (TextUtils.isEmpty(binding.input.text.toString())) {
                showToast("请输入评论")
            } else if (selectedFilesAll.isEmpty()) {
                showToast("至少选择一张图片")
            } else {
                //提交评论
                mViewModel.getTencentCredentials()
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        //清理资源
        releaseBitmapResources()
        // 修复：调用adapter的releaseResources方法释放图片资源
        mChoosePicAdapter?.releaseResources()
        mChoosePicAdapter = null
        mActivityResultLauncherAlbum = null
        takePhoto = null
    }

    private fun releaseBitmapResources() {
        // 清理URI集合
        selectedFilesAll.clear()

        // 清理压缩文件路径集合
        compressedImagePaths.clear()

        // 优化：释放临时文件资源
        try {
            for (path in compressedImagePaths) {
                val file = File(path)
                if (file.exists() && file.isFile) {
                    file.delete()
                }
            }
        } catch (e: Exception) {
            Log.e("OrderComment", "删除临时文件失败", e)
        }
    }
}